package com.loubobooo.personal.blog.controller.backend;

import com.loubobooo.personal.blog.entity.Tag;
import com.loubobooo.personal.blog.entity.vo.TagVO;
import com.loubobooo.personal.blog.service.ArticleService;
import com.loubobooo.personal.blog.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller @RequestMapping("/admin/tag") public class TagManageController {
    @Autowired private ArticleService articleService;

    @Autowired private TagService tagService;

    //后台标签列表显示
    @RequestMapping(value = "") public ModelAndView index() {
        ModelAndView modelandview = new ModelAndView();

        List<TagVO> tagVOList = tagService.listTag(null);
        modelandview.addObject("tagVOList", tagVOList);

        modelandview.setViewName("Admin/Tag/index");
        return modelandview;

    }

    //后台添加分类页面显示
    @RequestMapping(value = "/insertSubmit", method = RequestMethod.POST) public String insertTagSubmit(Tag tag) {
        tagService.insertTag(tag);
        return "redirect:/admin/tag";
    }

    //删除标签
    @RequestMapping(value = "/delete/{id}") public String deleteTag(@PathVariable("id") Integer id) {

        //禁止删除有文章的分类
        int count = articleService.countArticleWithTag(null, id);
        if (count == 0) {
            tagService.deleteTag(id);
        }
        return "redirect:/admin/tag";
    }

    //编辑标签页面显示
    @RequestMapping(value = "/edit/{id}") public ModelAndView editTagView(@PathVariable("id") Integer id) {
        ModelAndView modelAndView = new ModelAndView();

        TagVO tagVO = tagService.getTagById(id);
        modelAndView.addObject("tagVO", tagVO);

        List<TagVO> tagVOList = tagService.listTag(null);
        modelAndView.addObject("tagVOList", tagVOList);

        modelAndView.setViewName("Admin/Tag/edit");
        return modelAndView;
    }

    //编辑标签提交
    @RequestMapping(value = "/editSubmit", method = RequestMethod.POST) public String editTagSubmit(Tag tag) {
        tagService.updateTag(tag);
        return "redirect:/admin/tag";
    }
}
